<template>
  <BMap
    ref="map"
    enable-scroll-wheel-zoom
    :center="location.point || undefined"
    width="120%"
    height="400px"
    @initd="browser.get"
    @click="handleClick"
  >
    <template v-if="!isLoading">
      <!-- 标点 -->
      <BMarker :position="myPoint"></BMarker>
      <!-- 信息框 -->
      <BInfoWindow
        :show="true"
        :position="myPoint"
        title="地址信息"
        enable-auto-pan
        enable-close-on-click
        style="position: relative"
      >
        <div style="width: 100%; height: 50px">
          地址：{{ address }} 最匹配地点:{{ title || '无' }}
        </div>
        <div style="position: absolute; right: 0; bottom: 0">
          <div class="confirm" @click="confirmAddress">确认</div>
        </div>
      </BInfoWindow>
      <!-- 范围圈 -->
      <BCircle
        stroke-style="solid"
        stroke-color="#0099ff"
        :stroke-opacity="0.8"
        fill-color="#0099ff"
        :fill-opacity="0.5"
        :center="location.point"
        :radius="location.accuracy"
      />
    </template>
  </BMap>
</template>

<script setup lang="ts">
import {
  ref,
  reactive,
  toRefs,
  watch,
  onMounted,
  getCurrentInstance,
} from 'vue'
import {
  BMap,
  usePointGeocoder,
  PointGeocoderResult,
  useBrowserLocation,
} from 'vue3-baidu-map-gl'
/**
 * 创建map对象
 */
const map = ref()
/**
 * 创建经纬坐标
 */
const myPoint = ref({
  lat: '',
  lng: '',
})
/**
 * 创建存放地址和匹配地点
 */
const address = ref()
const title = ref()
/**
 * 初始化定位
 */
const browser = useBrowserLocation(null, () => {
  map.value.resetCenter()
})
const { location, isLoading } = toRefs(browser)
const { get, result } = usePointGeocoder<PointGeocoderResult>()

/**
 * 监听点击后的地址变化,重新赋值
 */
watch(
  () => result.value?.address,
  () => {
    address.value = result.value?.address
    title.value = result.value?.surroundingPois[0]?.title
  }
)
/**
 * 开关,只控制初始页面后的定位
 */
const state = ref(true)
/**
 *监听经纬的变化(初始化页面防止标点不出现)
 */
watch(
  () => location.value.point,
  () => {
    // 赋值,防止小标点不出现
    myPoint.value = location.value.point as any
    //只调用一次(初始化页面定位后触发,获取到定位后的位置信息以及打上标点)
    if (state.value) {
      get(myPoint.value as any)
      state.value = false
    }
  }
)

/**
 * 点击地图触发函数
 * @param e
 */
function handleClick(e: any) {
  myPoint.value = e.latlng

  get(e.latlng)
}
/**
 * 子传父将合并的地址传出去
 */
const confirmAddress = () => {
  const addTotal = address.value + title.value
  emit('addressTotal', addTotal)
}

const emit = defineEmits(['addressTotal'])
const props = defineProps({
  propData: {
    type: String,
    default: '',
  },
})
</script>
<style lang="scss" scoped>
.confirm {
  width: 50px;
  height: 20px;
  padding: 2px 0;
  background-color: #f56c6c;
  text-align: center;
  border-radius: 6px;
  line-height: 20px;
  cursor: pointer;
}
:deep(.anchorBL) {
  display: none !important;
}
</style>
